package com.lc.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.lc.admin.base.PageResponse;
import com.lc.admin.bean.LoginUserDetails;
import com.lc.admin.constants.DeptConstants;
import com.lc.admin.dto.PendingTaskDto;
import com.lc.admin.service.ApplicatService;
import com.lc.admin.utils.StringUtils;
import com.lc.admin.utils.UserThreadLocal;
import com.lc.admin.vo.PendingTaskVO;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 查询我的申请
 *   "code": "",//单据编号
 *   "endTime": "",//结束时间
 *   "pageNum": 0, //当前页码
 *   "pageSize": 0, //每页显示条数
 *   "startTime": "", //开始时间
 *   "status": 0, //单据状态（申请中、已完成、已关闭）
 *   "type": 0    //单据类别
 */
@Service
public class ApplicateServiceImpl implements ApplicatService {

    @Autowired
    HistoryService historyService;

    @Override
    public PageResponse<List<PendingTaskVO>> selectByPage(PendingTaskDto pendingTaskDto) {

        HistoricTaskInstanceQuery hisQuery = historyService.createHistoricTaskInstanceQuery();
        // 过滤我自己的数据，取出当前登录用户的信息
        // 你是养老顾问，查询%-1的
        // 如果你是护理主管，查询%-3
        LoginUserDetails user = UserThreadLocal.getUser();
        if(user.getPostNo().equals(DeptConstants.GUWEN_DEPT_NO)) {
            hisQuery.taskNameLike("%-1");
        } else if(user.getPostNo().equals(DeptConstants.NURSE_MANAGER_DEPT_NO)) {
            hisQuery.taskNameLike("%-3");
        }
        hisQuery.taskAssignee(user.getId()+"");

        // 封装条件
        // 再添加一个申请测试一下
        if(StringUtils.isNotEmpty(pendingTaskDto.getCode())){
            hisQuery.processVariableValueEquals("code",pendingTaskDto.getCode());
        }
        // 申请时间
        if(ObjectUtil.isNotEmpty(pendingTaskDto.getStartTime()) && ObjectUtil.isNotEmpty(pendingTaskDto.getEndTime())) {
            hisQuery.taskCreatedAfter(pendingTaskDto.getStartTime()).taskCreatedBefore(pendingTaskDto.getEndTime());
        } else if(ObjectUtil.isNotEmpty(pendingTaskDto.getStartTime()) && ObjectUtil.isEmpty(pendingTaskDto.getEndTime())) {
            hisQuery.taskCreatedAfter(pendingTaskDto.getStartTime());
        } else if(ObjectUtil.isEmpty(pendingTaskDto.getStartTime()) && ObjectUtil.isNotEmpty(pendingTaskDto.getEndTime())) {  // 只有结束时间
            hisQuery.taskCreatedBefore(pendingTaskDto.getEndTime());
        }
        if(ObjectUtil.isNotEmpty(pendingTaskDto.getStatus())) {    //流程状态（1：申请中，2:已完成，3:已关闭）
            hisQuery.processVariableValueEquals("status",pendingTaskDto.getStatus());
        }

        if(ObjectUtil.isNotEmpty(pendingTaskDto.getType())) {
            hisQuery.processVariableValueEquals("type",pendingTaskDto.getType());
        }

        // 获取总条数
        long count = hisQuery.includeProcessVariables().count();

        // 分页查询
        List<HistoricTaskInstance> tasks = hisQuery.includeProcessVariables().listPage((pendingTaskDto.getPageNum() - 1) * pendingTaskDto.getPageSize(), pendingTaskDto.getPageSize());

        // 封装VO
        List<PendingTaskVO> taskVos = new ArrayList<>();
        for (HistoricTaskInstance task : tasks) {
            Map<String, Object> variables = task.getProcessVariables();
            PendingTaskVO taskVo = new PendingTaskVO();
            taskVo.setId(task.getId());
            taskVo.setAssignee(variables.get("user0Name").toString());
            taskVo.setCheckInId(variables.get("checkInId").toString());
            taskVo.setApplicationTime(task.getCreateTime());
            taskVo.setCode(variables.get("code").toString());
            taskVo.setStatus(Integer.parseInt(variables.get("status").toString()));
            taskVo.setAssigneeId(task.getAssignee());
            taskVo.setTitle(variables.get("title").toString());
            taskVo.setType(Integer.parseInt(variables.get("type").toString()));

            taskVos.add(taskVo);
        }

        long pages = count % pendingTaskDto.getPageSize() == 0 ? count / pendingTaskDto.getPageSize() : count / pendingTaskDto.getPageSize() + 1;
        // 转换成PageResponse即可
        PageResponse of = PageResponse.of(taskVos, pendingTaskDto.getPageNum(), pendingTaskDto.getPageSize(), pages, count);
        return of;
    }
}
